<template>
  <div class="bi-qrcode" :style="style">
    <ui-loading class="bi-qrcode__loading" v-if="loading" color="#999"></ui-loading>
    <canvas class="bi-qrcode__image" v-show="!loading" ref="canvas"></canvas>
  </div>
</template>
<script>
import UiLoading from '../../components/loading'

export default {
  name: 'BiQrcode',
  components: {
    UiLoading
  },
  props: {
    width: {
      type: String
    },
    height: {
      type: String
    },
    content: {
      type: String
    }
  },
  data () {
    return {
      loading: false
    }
  },
  computed: {
    style () {
      const sy = {}
      if (this.width) {
        sy.width = this.width
      }
      if (this.height) {
        sy.height = this.height
      }
      return sy
    }
  },
  watch: {
    content () {
      this.loadImage()
    }
  },
  mounted () {
    this.loadImage()
  },
  methods: {
    loadImage () {
      this.loading = true
      this.generateQrcode(this.content).then(() => {
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    generateQrcode (content) {
      return new Promise((resolve, reject) => {
        import('qrcode').then((module) => {
          const QRCode = module.default
          QRCode.toCanvas(this.$refs.canvas, content, (error) => {
            if (error) {
              reject()
            } else {
              resolve()
            }
          })
        }, reject)
      })
    }
  }
}
</script>
<style lang="less">
.bi-qrcode{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.bi-qrcode__image{
  display: inline-block;
  vertical-align: top;
}
</style>
